# api/routes.py
from flask import Blueprint, request, jsonify, Response
import subprocess
import json

import config.config as config
from logger.logger import ns3_logger, ros_logger
import ros_bridge.ros_node as ros_node

# 创建 Blueprint，所有接口前缀为 /api
api_bp = Blueprint('api', __name__, url_prefix='/api')

@api_bp.route('/network/config', methods=['POST'])
def configure_network():
    """设置仿真参数（例如机器人数量等）。"""
    data = request.get_json(force=True)
    if not data:
        return jsonify({"error": "未提供配置参数"}), 400

    num_robots = data.get("num_robots")
    if num_robots is not None:
        config.settings["num_robots"] = int(num_robots)
    # 可根据需要处理其他参数
    ns3_logger.info(f"仿真参数更新：{json.dumps(data)}")
    return jsonify({"status": "configured", "config": config.settings})

@api_bp.route('/network/start', methods=['POST'])
def start_simulation():
    """启动 NS-3 仿真容器并启动 ROS2 监听。"""
    if config.settings.get("simulation_running"):
        return jsonify({"error": "仿真已在运行"}), 400

    robot_count = config.settings.get("num_robots", 1) or 1
    ros_node.start_ros_thread(robot_count=robot_count)

    cmd = [config.NS3_RUN_SCRIPT, str(robot_count)]
    try:
        log_file = open('ns3.log', 'w')
        config.simulation_process = subprocess.Popen(cmd, stdout=log_file, stderr=subprocess.STDOUT)
    except Exception as e:
        ros_logger.error(f"启动 NS-3 容器失败：{e}")
        return jsonify({"error": "启动仿真容器失败"}), 500

    config.settings["simulation_running"] = True
    ns3_logger.info("仿真容器已启动。")
    return jsonify({"status": "simulation started", "num_robots": robot_count})

@api_bp.route('/network/stop', methods=['POST'])
def stop_simulation():
    """停止 NS-3 仿真容器。"""
    if not config.settings.get("simulation_running"):
        return jsonify({"error": "当前无仿真运行"}), 400

    try:
        if config.simulation_process:
            config.simulation_process.terminate()
            config.simulation_process = None
    except Exception as e:
        ros_logger.error(f"停止仿真出错：{e}")
        return jsonify({"error": "停止仿真失败"}), 500

    config.settings["simulation_running"] = False
    ns3_logger.info("仿真容器已停止。")
    return jsonify({"status": "simulation stopped"})

@api_bp.route('/robots', methods=['GET'])
def get_robots():
    """获取机器人列表及其当前状态。"""
    robot_count = config.settings.get("num_robots", 0)
    robots = []
    for i in range(1, robot_count + 1):
        status = "ACTIVE" if config.settings.get("simulation_running") else "INACTIVE"
        robots.append({"id": i, "status": status})
    return jsonify(robots)

@api_bp.route('/logs/ros', methods=['GET'])
def get_ros_logs():
    """获取 ROS 相关日志。"""
    try:
        with open('ros.log', 'r') as f:
            log_content = f.read()
    except FileNotFoundError:
        log_content = "(ROS 日志为空或尚未创建)"
    return Response(log_content, mimetype='text/plain')

@api_bp.route('/logs/ns3', methods=['GET'])
def get_ns3_logs():
    """获取 NS-3 仿真日志。"""
    try:
        with open('ns3.log', 'r') as f:
            log_content = f.read()
    except FileNotFoundError:
        log_content = "(NS-3 日志为空或仿真未启动)"
    return Response(log_content, mimetype='text/plain')
